//
//  ZYUserAccountViewModel.swift
//  weiboZY
//
//  Created by 赵勇 on 16/5/12.
//  Copyright © 2016年 赵勇. All rights reserved.
//

import UIKit

class ZYUserAccountViewModel: NSObject {

    // 单例
    static let sharedUserAccount:ZYUserAccountViewModel = ZYUserAccountViewModel()
    // 保存用户对象
    var userAccount:ZYUserAcount?
    // 获取归档对象
    override init() {
        super.init()
        userAccount = ZYUserAcount.loadUserAccount()
    }
    
    // 只读属性  判断是否登录
    var isLogin:Bool {
        
        return accessToken != nil
    }
    
    //然后判断是否过期
    var accessToken:String? {
        // 首先判断token是否存在

        guard let token = userAccount?.access_token else {
            return nil
        }
        // 然后判断是否过期，过期需要重新登录
        let result = userAccount?.expiresDate?.compare(NSDate())
        if result == NSComparisonResult.OrderedDescending {
            return token
        } else {
            return nil
        }
    }
    
    // 通过code获取accessToken
    func requestAccessToken(code:String, complete:(isSuccess: Bool)->()) {
        // 网络工具类请求数据
        ZYNetWorkTools.sharedTool.requestAccessToken(code) { (response, error) -> () in
            
            if error != nil {
                print("网络请求异常")
                complete(isSuccess: false)
                return
            }
            // 代码执行到此，网络请求成功
            guard let dict = response as? [String:AnyObject] else {
                print("数据不是字典")
                complete(isSuccess: false)
                return
            }
            
            //  字典存在（字典转模型）
            let userAcount = ZYUserAcount(dict: dict)
            //            print(userAcount)
            self.requestUserInfo(userAcount,complete: complete)
        }
    }
    
    
    // 获取用户个人信息
    func requestUserInfo(userAcount:ZYUserAcount, complete:(isSuccess: Bool)->()) {
        
        // 网络工具类请求数据
        ZYNetWorkTools.sharedTool.requestUserInfo(userAcount) { (response, error) -> () in
            if error != nil {
                print("网络请求异常")
                 complete(isSuccess: false)
                return
            }
            
            guard let dict = response as? [String:AnyObject] else {
                print("数据不是字典")
                 complete(isSuccess: false)
                return
            }
            
            // 给模型赋值
            userAcount.name = dict["name"] as? String
            userAcount.avatar_large = dict["avatar_large"] as? String
            
            self.userAccount = userAcount
            
            
            // 归档
            let result = userAcount.saveUserAccount()
            
            if result {
                // 归档成功
               complete(isSuccess: true)
            } else {
                // 归档失败
               complete(isSuccess: false)
            }
        }
        
    }
}

